<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <div>
          <a-form
            size="small"
            :model="pageData"
            layout="inline"
            v-if="permissionStore.hasPermisson('bygjzdlb.cx')"
          >
            <a-form-item label="计件单号" label-col-flex="70px" :style="{ width: '315px' }">
              <a-input
                allow-clear
                class="bacClass"
                v-model="pageData.dropDownData"
                @press-enter="huiche"
              ></a-input>
            </a-form-item>
            <a-form-item label="计件日期" label-col-flex="70px" :style="{ width: '315px' }">
              <a-range-picker
                popup-container="html"
                class="bacClass"
                @select="onSelect"
                @clear="onClear"
              />
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar">
          <Toolbar
            class="gesture"
            :items="pageData.btnList"
            @add="addHandler"
            @del="deleteHandler"
            @select="selectHandler"
            @export="exports"
            @cel="toVoid"
            style="float: right"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-space style="float: right; z-index: 9999"> </a-space>
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <AgGridVuesCopys
          :rowHeight="33"
          :headerHeight="33"
          rowSelection="multiple"
          @grid-ready="gridReady"
          style="height: calc(100% - 45px)"
          :defaultColDef="defaultColDef"
          class="ag-theme-alpine"
          :rowData="table.dataList"
          :localeText="localeText1"
          :columnDefs="tc"
        ></AgGridVuesCopys>
        <paginationCopys
          :total="total"
          show-total
          show-jumper
          show-page-size
          @change="PageSize"
          @page-size-change="change1"
          style="justify-content: center"
          :page-size="size"
          :current="page"
        />
      </a-spin>
    </template>

    <a-drawer
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 999 }"
      :mask-closable="false"
      :width="400"
      unmount-on-close
      popup-container=".arco-tabs-content"
      placement="bottom"
      :height="pageData.rHeight"
      :ok-loading="pageData.pageLoading"
      :visible="pageData.showAdd"
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div style="height: 50px">
        <a-form size="small" :model="dataForm" layout="inline" ref="formRef">
          <!-- <a-form-item label="登记日期">
                        <a-date-picker  popup-container="html"  class="bacClass" v-model="dataForm.registerTime" />
                    </a-form-item> -->
          <!-- <a-form-item label="登记单号">
                        <a-select popup-container="html"  :style="{ width: '200px' }" :loading="loading" @search="handleSearch" class="bacClass"
                            v-model="pageData.dropDownData" :filter-option="false" allow-search allow-clear
                            @focus="focusSel">
                            <a-option v-for="item in pageData.nameList" :value="item">{{ item }}</a-option>
                        </a-select>
                    </a-form-item> -->
          <CorporateSectorCascader
            v-if="dataForm.autoState != 1"
            ref="cascaderRef"
            :configCascader="configCascader"
            @changeCascader="changeCascader"
          />
          <a-form-item label-col-flex="100px" label="搬运项目" v-if="dataForm.autoState != 1">
            <!-- <a-input allow-clear :style="{ width: '200px' }" class="bacClass" v-model="dataForm.companyName"></a-input> -->
            <a-select
              popup-container="html"
              :style="{ width: '200px' }"
              :loading="loading"
              @search="handleSearchCpj"
              class="bacClass"
              v-model="dataForm.carryProjectName"
              :filter-option="false"
              allow-search
              allow-clear
              @focus="focusSelCpj"
              @change="changeCpj"
            >
              <a-option v-for="item in pageData.cpjList" :value="item.transportName">{{
                item.transportName
              }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label-col-flex="100px" label="单位" v-if="dataForm.autoState != 1">
            <a-input
              allow-clear
              :style="{ width: '200px' }"
              class="bacClass"
              v-model="dataForm.unit"
              :disabled="true"
            ></a-input>
          </a-form-item>
          <a-form-item label-col-flex="100px" label="单价" v-if="dataForm.autoState != 1">
            <a-input
              allow-clear
              :style="{ width: '200px' }"
              class="bacClass"
              v-model="dataForm.price"
              :disabled="true"
            ></a-input>
          </a-form-item>
          <a-form-item label-col-flex="100px" label="总数量" v-if="dataForm.autoState != 1">
            <a-input
              allow-clear
              :style="{ width: '200px' }"
              class="bacClass"
              v-model="dataForm.totalNum"
              @change="totalNumClick"
            ></a-input>
          </a-form-item>
          <a-form-item label-col-flex="100px" label="计件工资" v-if="dataForm.autoState != 1">
            <a-input
              allow-clear
              :style="{ width: '200px' }"
              class="bacClass"
              v-model="dataForm.pieceWage"
              :disabled="true"
            ></a-input>
          </a-form-item>
          <a-form-item
            label-col-flex="100px"
            label="公司"
            v-if="pageData.sideTitle != '新增搬运件资单' && dataForm.autoState == 1"
          >
            <a-input
              allow-clear
              :style="{ width: '200px' }"
              class="bacClass"
              v-model="dataForm.companyName"
              :disabled="true"
            ></a-input>
          </a-form-item>
          <a-form-item
            label-col-flex="100px"
            label="部门"
            v-if="pageData.sideTitle != '新增搬运件资单' && dataForm.autoState == 1"
          >
            <a-input
              allow-clear
              :style="{ width: '200px' }"
              class="bacClass"
              v-model="dataForm.departmentName"
              :disabled="true"
            ></a-input>
          </a-form-item>
        </a-form>
      </div>
      <div style="height: calc(100% - 80px); margin-top: 20px">
        <a-space style="margin-bottom: 10px">
          <a-button type="primary" @click="addLine" size="mini">选择员工</a-button>
          <a-button type="primary" @click="delLine" size="mini">删除</a-button>
        </a-space>
        <a-space
          v-if="pageData.sideTitle != '新增搬运件资单' && dataForm.autoState == 1"
          style="margin-bottom: 10px; font-size: 16px; color: red"
        >
          <span>总数量：{{ dataForm.totalNum }}</span>
          <!-- <span style="margin: 0 10px">总条数：{{ pageData.totalNumber }}</span> -->
          <span>总计件工资：{{ dataForm.pieceWage }}</span>
        </a-space>
        <!-- <a-table stripe :bordered="true" :columns="tableColumns1" size="mini"
          :row-selection="{ showCheckedAll: true, width: 50 }" v-model:selected-keys="s" :loading="table.tableLoading"
          :data="pageData.list" rowKey="carryStaffId">
          <template #workCoefficient="{ record }">
            <div style="width: 100%">
              <a-input-number class="bacClass" v-model="record.workCoefficient" @change="workChanges" :precision="2" />
            </div>
          </template>
        </a-table> -->

        <AgGridVuesCopys
          :rowHeight="33"
          :headerHeight="33"
          :suppressCopyRowsToClipboard="true"
          rowSelection="multiple"
          @grid-ready="gridReadyw"
          style="height: 100%"
          :defaultColDef="defaultColDef"
          class="ag-theme-alpine"
          :rowData="pageData.list"
          :localeText="localeText1"
          :columnDefs="tc1"
        ></AgGridVuesCopys>
      </div>
    </a-drawer>
    <a-modal
      v-model:visible="visible"
      title="选择搬运人员"
      @cancel="handleCancel"
      :draggable="true"
    >
      <a-form :model="pageData" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
        <!-- <CorporateSectorCascader ref="cascaderRef1" :configCascader="configCascader" @changeCascader="changeCascader1" /> -->
        <!-- <a-form-item label="搬运人员">
          <a-select popup-container="html"  class="bacClass" v-model="pageData.dismantlingSheetNumber" multiple @focus="getPersonnel"
            style="width:250px;">
            <a-option v-for="(item, index) in pageData.dismantlingSheetNumberList" :value="item['id']">
              {{ item.name }}
            </a-option>
          </a-select>
        </a-form-item> -->
        <a-table
          row-key="name"
          :columns="columns"
          :data="dataListDeff"
          v-model:selectedKeys="selectedKeys"
          :pagination="false"
          :row-selection="rowSelection"
        />
      </a-form>
      <template #footer>
        <a-button type="primary" size="small" @click="handleOk">确定</a-button>
      </template>
    </a-modal>
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post, get } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import emitter from '@/hooks/useEventBus'
  import { ref, reactive, onMounted, toRefs, nextTick } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Button, Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import { baseURL } from '../../../api/axios.config'
  import axios from 'axios'
  import filedownload from 'js-file-download'
  import usePermission from '@/store/modules/permission'
  import PageTabelLayout from '@/components/pageTabelLayout.vue'
  import MyTable from '@/components/MyTable'
  import ButtonRenderer from '@/components/TableCellRenderer/ButtonRenderer'
  import { template } from 'lodash'
  import { setupGlobalComponent } from '@/layouts'
  // 引入
  
  import { localeText } from '@/api/aggridZw'
  import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
  import dayjs from 'dayjs'

  interface DismantlingPayroll {
    id: any
    serialNumber: any
    carryNumber: string
    remark: string
    createName: string
    createTime: string
    updateName: string
    updateTime: string
    firmGroupId: any
    carryType: string
    carryProjectName: string
    price: any
    weight: any
    number: any
    staffId: string
    pieceMoney: any
    staffName: string
    company: string
    firmGroupsId: any
    firmId: any
    firm: any
    departmentId: any
    department: any
  }

  export default {
    name: 'HandlingList2',

    setup() {
      const total = ref(0)
      const page = ref(1)
      const size = ref(10)
      function PageSize(val: any) {
        page.value = val
        doRefresh()
      }
      function change1(val: any) {
        size.value = val
        doRefresh()
      }
      const headerShow = ref<boolean>(true)
      let cascaderRef: any = ref('')
      let configCascader = ref<{}>({
        corporateWidth: '200px', //公司宽度
        sectorWidth: '200px', //部门宽度
        corporateRquired: true, //公司是否必填
        sectorRquired: true, //部门是否必填
        size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
        corporateName: '公司', //公司label
        sectorName: '部门', //部门label,
        corporateNameLabelWidth: '100px',
        sectorLabelWidth: '100px',
      })
      const changeCascader = (data: any) => {
        const { corporateId, sectorId, sectorLabel, corporateLabel } = data
        dataForm.companyId = corporateId
        dataForm.companyName = corporateLabel
        dataForm.departmentId = sectorId
        dataForm.departmentName = sectorLabel
      }
      let cascaderRef1 = ref('')
      const changeCascader1 = (data: any) => {
        const { corporateId, sectorId } = data
        pageData.firmId = corporateId
        pageData.departmentId = sectorId
      }
      function doRefresh() {
        pageData.pageLoading = true
        post({
          url: '/pieceData/CarryStaffPiece/getPage',
          data: {
            page: page.value,
            size: size.value,
            pieceCode: pageData.dropDownData,
            beginDate: pageData.registerTime,
            endDate: pageData.registerTime2,
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              table.handleSuccess(data.list)
              // 查询方法改
              gridOption.value.setRowData(data.list)
              total.value = data.total
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }

      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const selectedRowKeys1 = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')
      const tableColumns = useTableColumn([
        {
          title: '公司',
          key: 'companyName',
          dataIndex: 'companyName',
          width: 150,
        },
        {
          title: '部门',
          key: 'departmentName',
          dataIndex: 'departmentName',
          width: 150,
        },
        {
          title: '计件单号',
          key: 'pieceCode',
          dataIndex: 'pieceCode',
          width: 150,
        },
        {
          title: '计件日期',
          key: 'pieceDate',
          dataIndex: 'pieceDate',
          width: 150,
        },
        {
          title: '单位',
          key: 'unit',
          dataIndex: 'unit',
          width: 150,
        },
        {
          title: '搬运项目名称',
          key: 'carryProjectName',
          dataIndex: 'carryProjectName',
          width: 150,
        },
        {
          title: '单价',
          key: 'price',
          dataIndex: 'price',
          width: 150,
        },
        {
          title: '搬运员工',
          key: 'carryStaffName',
          dataIndex: 'carryStaffName',
          width: 150,
        },
        {
          title: '计件工资',
          key: 'pieceWage',
          dataIndex: 'pieceWage',
          width: 150,
        },
        {
          title: '总出勤系数',
          key: 'workCoefficient',
          dataIndex: 'workCoefficient',
          width: 150,
        },
        {
          title: '总数量',
          key: 'totalNum',
          dataIndex: 'totalNum',
          width: 150,
        },
        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
          width: 150,
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
          width: 200,
        },
        {
          title: '最后修改人',
          key: 'updateName',
          dataIndex: 'updateName',
          width: 150,
        },
        {
          title: '最后修改时间',
          key: 'updateTime',
          dataIndex: 'updateTime',
          width: 200,
        },
        {
          title: '是否自动生成',
          key: 'autoState',
          dataIndex: 'autoState',
          width: 150,
          fixed: 'right',
          slotName: 'autoState',
        },
        // {
        //   title: '作废状态',
        //   key: 'toState',
        //   dataIndex: 'toState',
        //   width: 100,
        //   fixed: 'right',
        //   slotName: 'toState',
        // },
        {
          title: '操作',
          key: 'act',
          slotName: 'act',
          width: 100,
          fixed: 'right',
        },
      ])

      let tc: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }
        if (o.slotName === 'act') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 120
          obj['cellRenderer'] = {
            // template: `<a-tag color="#ff7d00" v-if="isEdit" class="gesture" @click="a" v-if="e">修改</a-tag>`,
            template: `<el-button style="color:#165dff;" link   @click="a">修改</el-button>`,

            setup(props: any) {
              const a = () => {
                editHandler(props.params.data)
              }
              return {
                a,
              }
            },
          }
        }
        if (o.slotName === 'toState') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 120
          obj['cellRenderer'] = {
            template: `<a-space>
            <el-tag  type="info" v-if="params.data.toState==1">{{val}}</el-tag>
            <el-tag  type="success" v-else>{{val}}</el-tag>
          </a-space>`,

            setup(props: any) {
              let val = ref()
              if (props.params.data.toState == 0) {
                val.value = '未作废'
              } else {
                val.value = '已作废'
              }

              return {
                val,
              }
            },
          }
        }
        if (o.slotName === 'autoState') {
          obj['resizable'] = false
          obj['filter'] = true
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 150
          obj['cellRenderer'] = {
            template: `<a-space>
            <el-tag  type="success" v-if="params.data.autoState==1">{{val}}</el-tag>
            <el-tag  type="info" v-else>{{val}}</el-tag>
          </a-space>`,

            setup(props: any) {
              let val = ref()
              if (props.params.data.autoState == 0) {
                val.value = '否'
              } else {
                val.value = '是'
              }

              return {
                val,
              }
            },
          }
          obj['filterParams'] = {
            valueFormatter: function (params) {
              return params.value == '0' ? '否' : params.value == '1' ? '是' : ''
            },
          }
        }

        return obj
      })

      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)

      const tableColumns1 = useTableColumn([
        {
          title: '序号',
          key: 'serialNo',
          dataIndex: 'serialNo',
          width: 150,
        },

        {
          title: '搬运项目名称',
          key: 'carryProjectName',
          dataIndex: 'carryProjectName',
          width: 150,
          slotName: 'carryProjectName',
        },
        {
          title: '单价',
          key: 'price',
          dataIndex: 'price',
          width: 150,
        },
        {
          title: '单位',
          key: 'unit',
          dataIndex: 'unit',
          width: 150,
        },
        {
          title: '总数量',
          key: 'totalNum',
          dataIndex: 'totalNum',
          width: 150,
        },
        {
          title: '计件工资',
          key: 'pieceWage',
          dataIndex: 'pieceWage',
          width: 150,
        },
        {
          title: '搬运员工',
          key: 'carryStaffName',
          dataIndex: 'carryStaffName',
          width: 150,
          slotName: 'carryStaffName',
        },
        {
          title: '出勤系数',
          key: 'workCoefficient',
          dataIndex: 'workCoefficient',
          width: 150,
          slotName: 'workCoefficient',
        },
        {
          title: '金额',
          key: 'amount',
          dataIndex: 'amount',
          width: 150,
          slotName: 'amount',
        },
      ])

      let tc1: any[] = tableColumns1.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }
        // if (o.slotName === 'act') {
        //   obj['resizable'] = false
        //   obj['filter'] = false
        //   obj['sortable'] = false
        //   obj['lockPosition'] = 'right'

        //   obj['cellRenderer'] = {
        //     template: `<div color="#ff7d00" class="gesture" @click="a"></div>`,
        //     setup(props: any) {
        //       const a = () => {
        //         if (
        //           props.params.data.staffId != '' &&
        //           props.params.data.staffId != null &&
        //           props.params.data.staffId != undefined
        //         ) {
        //           props.params.data
        //           getFirmGroup()
        //           getPersonnel()
        //         }

        //         visible.value = true
        //       }
        //       return {
        //         a,
        //       }
        //     },
        //   }
        // }
        if (o.slotName == 'workCoefficient') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false

          obj['cellRenderer'] = {
            template: `<a-input-number class="bacClass" v-model="params.data.workCoefficient" @change="a" :precision="2" size="mini" />`,
            setup(props: any) {
              const a = (event: any) => {
                workChanges(event)
              }
              return {
                a,
              }
            },
          }
        }

        return obj
      })

      tc1 = a.concat(tc1)
      const pageData = reactive<{
        showAdd: boolean
        sideTitle: string
        dropDownData: any
        nameList: []
        pageLoading: boolean
        typeList: []
        dropDownData1: any
        rHeight: any
        btnList: any[]
        isEdit: boolean
        dismantlingSheetNumber: any[]
        dismantlingSheetNumberList: any[]
        addDataList: any[]
        list: any[]
        company: any
        firmList1: any[]
        firmList: any[]
        bmList: any[]
        bmList1: any[]
        bumen: any
        cpjList: any[]
        totalWages: any
        totalNumber: any
        totalWeight: any
        registerTime: any
        registerTime2: any
        nameList1: any[]
        departmentId: any
        firmId: any
      }>({
        nameList: [],
        showAdd: false,
        sideTitle: '新增拆纱工资单',
        dropDownData: '',
        pageLoading: false,
        typeList: [],
        dropDownData1: '',
        rHeight: 0,
        btnList: [],
        isEdit: false,
        dismantlingSheetNumber: [],
        dismantlingSheetNumberList: [],
        addDataList: [],
        list: [],
        company: '',
        firmList1: [],
        firmList: [],
        bmList: [],
        bmList1: [],
        bumen: null,
        cpjList: [],
        totalWages: 0,
        totalNumber: 0,
        totalWeight: 0,
        registerTime: '',
        registerTime2: '',
        nameList1: [],
        departmentId: '',
        firmId: '',
      })

      interface gcType {
        id: any
        company: any
      }
      let field = ''
      //下拉框得到焦点
      const focusSel = (val: any) => {
        field = val
        let ob = {}
        ob[field] = ''
        selCxAll(ob)
      }
      //下拉数据
      const options = ref<any>(pageData.nameList)
      const loading = ref(false)
      const handleSearch = (value: any) => {
        if (value) {
          const ob = { field: value }
          loading.value = true
          selCxAll(ob)
          options.value = pageData.nameList
          loading.value = false
        } else {
          options.value = []
        }
      }

      //下拉框查询
      function selCxAll(val: any) {
        post({
          url: 'pieceData/CarryPiece/findCarryPiece2',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            if (field == 'carryNumber') {
              pageData.nameList = data.items
            } else if (field == 'staffName') {
              pageData.nameList1 = data.items
            }
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }
      //下拉框得到焦点
      const focusSelCpj = () => {
        selCxAllCpj({ transportName: '' })
      }
      //下拉数据
      const optionsCpj = ref<any>(pageData.cpjList)
      const handleSearchCpj = (value: any) => {
        if (value) {
          const ob = { transportName: value }
          loading.value = true
          selCxAllCpj(ob)
          optionsCpj.value = pageData.cpjList
          loading.value = false
        } else {
          optionsCpj.value = []
        }
      }

      //下拉框查询
      function selCxAllCpj(val: any) {
        post({
          url: 'pieceData/transportPrice/getList',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            pageData.cpjList = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      onMounted(() => {
        // // 切换tap到本页面执行的方法
        // emitter.on("BrandInfo", () => {
        //     // selCxAll1({});
        //     doRefresh();
        // });
        pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight
        //弹出层的高
        if (pageData.rHeight !== undefined) {
          pageData.rHeight = pageData.rHeight - 100
        }
        window.addEventListener('resize', () => {
          pageData.rHeight = document.getElementsByClassName('arco-tabs-content')[0]?.clientHeight
          //弹出层的高
          if (pageData.rHeight !== undefined) {
            pageData.rHeight = pageData.rHeight - 100
          }
        })
      })
      let cxbl = ''
      //查询
      const selectHandler = () => {
        pagination.page = 1
        cxbl = pageData.dropDownData
        doRefresh()
      }
      const queryData = reactive({
        clothType: '',
      })
      const addHandler = () => {
        pageData.list = []
        for (var key in dataForm) {
          dataForm[key] = ''
        }
        // foucusUseFrim(1)
        // for (var key in dataForm) {
        //   if (key == 'id' || key == 'firmGroupId' || key == 'firmGroupsId') {
        //     dataForm[key] = null
        //   } else if (
        //     key == 'serialNumber' ||
        //     key == 'price' ||
        //     key == 'weight' ||
        //     key == 'number' ||
        //     key == 'pieceMoney'
        //   ) {
        //     dataForm[key] = 0
        //   } else {
        //     dataForm[key] = ''
        //   }
        // }
        // calculatedField()

        pageData.showAdd = true
        formRef.value?.resetFields()
        pageData.sideTitle = '新增搬运件资单'
      }
      let curobj = null
      const editHandler = (record: any) => {
        curobj = record
        // foucusUseFrim(1)
        //查这个单号所有的数据
        post({
          url: '/pieceData/CarryStaffPieceDetail/getList',
          data: {
            carryStaffPieceId: record.id,
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              pageData.list = data
              for (var key in record) {
                dataForm[key] = record[key]
              }
              // calculatedField()
              pageData.sideTitle = '修改搬运件资单'
              pageData.showAdd = true
              if (dataForm.autoState != 1) {
                nextTick(() => {
                  let data = {
                    sectorId: record.departmentId,
                    sectorLabel: record.departmentName,
                    corporateId: record.companyId,
                    corporateLabel: record.companyName,
                  }
                  cascaderRef.value?.parentComponent(data)
                })
              }
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }
      const dataForm: any = reactive({
        id: null,
        remark: '',
        createName: '',
        createTime: '',
        updateName: '',
        updateTime: '',
        serialNumber: 0,
        carryNumber: '',
        firmGroupId: null,
        carryType: '',
        carryProjectName: '',
        price: 0,
        weight: 0,
        number: 0,
        staffId: '',
        pieceMoney: 0,
        staffName: '',
        company: '',
        firmGroupsId: null,
        firmId: '',
        firm: '',
        departmentId: '',
        department: '',
      })

      // 表格准备事件
      const gridOption = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
      }

      // 表格准备事件
      const gridOptionw = ref()
      const gridReadyw = (params: any) => {
        gridOptionw.value = params.api
      }

      let formRef = ref<FormInstance>()
      const sideOk = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            if (pageData.list.length == 0) {
              Message.warning({
                content: '请新增一条搬运件资单列表！',
                duration: 5000,
              })
              return
            }
            // pageData.list.forEach(function (o: any) {
            //   if ((o['id'] + '').indexOf('add') != -1) {
            //     o['id'] = null
            //   }
            // })
            // let flag = false
            // pageData.list.forEach(function (o: any) {
            //   if (
            //     o['staffName'] == '' ||
            //     o['staffName'] == undefined ||
            //     o['staffName'] == null ||
            //     o['carryProjectName'] == '' ||
            //     o['carryProjectName'] == undefined ||
            //     o['carryProjectName'] == null
            //   ) {
            //     flag = true
            //   }

            //   o['pieceMoney'] = parseFloat(o['pieceMoney'])
            //   o['registerTime'] = dataForm['registerTime']
            //   o['firmId'] = dataForm['firmId']
            //   o['firm'] = dataForm['firm']
            //   o['department'] = dataForm['department']
            //   o['departmentId'] = dataForm['departmentId']
            //   if (
            //     (o['weight'] == 0 ||
            //       o['weight'] == undefined ||
            //       o['weight'] == null ||
            //       o['weight'] == '') &&
            //     (o['number'] == 0 ||
            //       o['number'] == undefined ||
            //       o['number'] == null ||
            //       o['number'] == '')
            //   ) {
            //     flag = true
            //   }
            // })
            // if (flag) {
            //   Message.warning({
            //     content: '每一行的条数、重量都要必填一个,员工、搬运项目必选',
            //     duration: 5000,
            //   })
            //   return
            // }
            pageData.pageLoading = true
            if (pageData.sideTitle === '新增搬运件资单') {
              post({
                url: '/pieceData/CarryStaffPiece/insertList',
                data: {
                  ...dataForm,
                  carryStaffPieceDetail: pageData.list,
                },
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    pageData.showAdd = false

                    Message.success({
                      content: '新增成功',
                      duration: 5000,
                    })
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                  doRefresh()
                  pageData.list = []
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
            } else {
              post({
                url: 'pieceData/CarryStaffPiece/updateList',
                data: {
                  ...dataForm,
                  carryStaffPieceDetail: pageData.list,
                },
              })
                .then((res: any) => {
                  if (res.code === 200) {
                    formRef.value?.resetFields()
                    pageData.showAdd = false

                    Message.success({
                      content: '修改成功',
                      duration: 5000,
                    })
                  } else {
                    Message.error({
                      content: res.message,
                      duration: 5000,
                    })
                  }
                  doRefresh()
                  pageData.list = []
                })
                .finally(() => {
                  pageData.pageLoading = false
                })
            }
          }
        })
      }
      const deleteHandler = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          Message.error('请先勾选')
          return
        }
        for (let i = 0; i < gridOption.value.getSelectedRows().length; i++) {
          if (gridOption.value.getSelectedRows()[i].autoState == 1) {
            Message.error('自动生成单据不可删除')
            return
          }
        }
        let list = gridOption.value.getSelectedRows()
        list.forEach(function (o: any) {
          o['deleteState'] = 1
        })
        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            pageData.pageLoading = true
            post({
              url: '/pieceData/CarryStaffPiece/delete',
              data: gridOption.value.getSelectedRows().map((res) => res.id),
            })
              .then(({ code, data }: any) => {
                if (code === 200) {
                  Message.success({
                    content: '删除成功',
                    duration: 5000,
                  })
                  pagination.page = 1
                  doRefresh()
                } else {
                  Message.error({
                    content: '删除失败',
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          },
        })
      }

      //导出
      const exports = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          Message.error('请先勾选')
          return
        } else {
          let idList: any = []
          gridOption.value.getSelectedRows().forEach(function (o: any) {
            idList.push(o['id'])
          })
          //将表头拼接出来
          let head =
            '<th>登记单号</th><th>搬运项目名称</th><th>单价</th><th>搬运员工</th><th>计件工资</th><th>登记日期</th><th>作废状态</th>' +
            '<th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>'
          //拿到当前表格数据与勾选的行做筛选

          let nowRow = table.dataList.filter(function (o) {
            return (
              gridOption.value
                .getSelectedRows()
                .map((o: any) => {
                  return o.id
                })
                .indexOf(o['id']) !== -1
            )
          })
          let body = ''
          nowRow.forEach(function (o) {
            body += '<tr><td>' + o['carryNumber'] + '</td>'
            body += '<td>' + o['carryProjectName'] + '</td>'
            body += '<td>' + o['price'] + '</td>'
            body += '<td>' + o['staffName'] + '</td>'
            body += '<td>' + o['pieceMoney'] + '</td>'
            body += '<td>' + o['registerTime'] + '</td>'
            body += '<td>' + (o['toState'] == 0 ? '未作废' : '已作废') + '</td>'
            body += '<td>' + o['createName'] + '</td>'
            body += '<td>' + o['createTime'] + '</td>'
            body += '<td>' + o['updateName'] + '</td>'
            body += '<td>' + o['updateTime'] + '</td>'
            body += '</tr>'
          })
          tableToXlsx(head, '搬运件资单', body)
        }
      }

      function tableToXlsx(head: any, filename: any, body: any) {
        const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

        const a = document.createElement('a')
        a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
        a.download = filename
        a.click()
        document.removeChild(a)
      }

      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        // flex: 1
      }

      //打开单号弹窗
      const visible = ref(false)
      const handleOk = () => {
        if (selectedKeys.value.length == 0) {
          Message.error({
            content: '请选择搬运员工',
            duration: 5000,
          })
          return
        }
        //以逗号形式将员工名称和员工id拼接
        // recordOb['staffId'] = pageData.dismantlingSheetNumber.join(',')
        // let list = pageData.dismantlingSheetNumberList.filter(function (o: any) {
        //   return pageData.dismantlingSheetNumber.includes(o['id'])
        // })
        // if (list.length > 0) {
        //   for (var i = 0; i < list.length; i++) {
        //     if (i == 0) {
        //       console.log(list[i])
        //       recordOb['empCode'] = list[i].code
        //       recordOb['staffName'] = list[i].name
        //     } else {
        //       recordOb['staffName'] += ',' + list[i].name
        //       recordOb['empCode'] += ',' + list[i].code
        //     }
        //   }
        // }
        // recordArrayCarryStaffName = dataListDeff.value.filter((res:any)=>{
        //      return selectedKeys.value.includes(res.carryStaffName)
        // })

        selectedKeys.value.forEach((xxx: any) => {
          pageData.list.push({
            serialNo:
              pageData.list.length == 0
                ? 1
                : Number(pageData.list[pageData.list.length - 1].serialNo) + 1,
            carryProjectName: dataForm.carryProjectName,
            price: dataForm.price,
            unit: dataForm.unit,
            totalNum: dataForm.totalNum,
            pieceWage: dataForm.pieceWage,
            carryStaffName: xxx,
            carryStaffId: dataListDeff.value.filter((res: any) => {
              return xxx == res.name
            })[0].id,
            workCoefficient: 1,
            amount: 0,
          })
        })
        jjgzooo(pageData.list)

        visible.value = false
      }
      const handleCancel = () => {
        visible.value = false
      }
      const localeText1: any = ref(localeText)
      let c = 0
      //成分添加一行 点击新增按钮
      const addLine = () => {
        selectedKeys.value = []
        //在这个数组前面添加一行
        // pageData.list.unshift({
        //   id: 'add' + c++,
        //   carryProjectName: '',
        //   price: 0,
        //   weight: 0,
        //   number: 0,
        //   'staffName ': '',
        //   staffId: null,
        //   pieceMoney: 0,
        // })

        if (!dataForm.companyId || !dataForm.departmentId) {
          Message.error('请先选择公司部门')
          return
        }
        if (!dataForm.carryProjectName) {
          Message.error('请先选择搬运项目')
          return
        }
        if (!dataForm.unit) {
          Message.error('请先选择单位')
          return
        }
        if (!dataForm.price) {
          Message.error('请先选择单价')
          return
        }
        if (!dataForm.totalNum) {
          Message.error('请先选择总数量')
          return
        }
        if (!dataForm.pieceWage) {
          Message.error('请先选择计件工资')
          return
        }
        post({
          url: 'org/hrEmployee/getUserAndSecondment',
          data: {
            department_id: dataForm.departmentId,
            workTime:dayjs().format('YYYY-MM-DD'),
          },
        }).then(({ code, data }) => {
          if (code == 200) {
            dataListDeff.value = data
            visible.value = true
          }
        })
      }
      //子表 删除
      const delLine = () => {
        if (gridOptionw.value.getSelectedRows().length === 0) {
          Message.error({
            content: '请先勾选',
            duration: 5000,
          })
          return
        }
        pageData['list'] = pageData['list'].filter(function (o: any) {
          return (
            gridOptionw.value
              .getSelectedRows()
              .map((res) => res.carryStaffId)
              .indexOf(o['carryStaffId']) === -1
          )
        })
        pageData['list'].forEach((res, inx) => {
          res.serialNo = inx + 1
        })
        jjgzooo(pageData['list'])
      }
      let recordOb = {}
      let recordArrayCarryStaffName: any = []
      let recordsAny: any = []
      //打开员工弹窗
      const openStaff = (record: any) => {
        recordsAny = record
        // pageData.company = ''
        // pageData.dismantlingSheetNumber = []
        // recordOb = record
        // pageData.dismantlingSheetNumber= record.staffId.split(',')
        post({
          url: '/pieceData/CarryStaffPiece/getPieceStaff',
          data: {
            companyId: dataForm.companyId,
            departmentId: dataForm.departmentId,
            notInIdList: [...pageData.list.map((res) => res.id)],
          },
        }).then(({ code, data }) => {
          if (code == 200) {
            dataListDeff.value = data
            selectedKeys.value = record.carryStaffName.split(',')
            visible.value = true
          }
        })
      }
      //拿到所有公司
      const foucusUseFrim = (num: any) => {
        let ob = {}
        if (num == 1) {
          ob['firmName'] = ''
          ob['department'] = ''
          // ob['firmTypeId'] = ""
        }
        if (num == 2) {
          if (dataForm.firmGroupsId !== '' && dataForm.firmGroupsId !== undefined) {
            let list = pageData.firmList.filter(function (o: any) {
              return o['id'] == dataForm.firmGroupsId
            })
            ob['firmName'] = list[0]['firmName']
            // dataForm.firmGroupsId = list[0]['typeName'] ? list[0]['typeName'] + '-' + list[0]['firmName'] : list[0]['firmName']
            ob['department'] = list[0]['department']
            ob['firmTypeId'] = list[0]['firmTypeId']
          } else {
            Message.warning({
              content: '请先选择公司',
              duration: 5000,
            })
          }
        }

        // getFrimList(ob, num)
      }
      const options2 = ref(pageData.firmList)
      const loading2 = ref(false)

      const handleSearch2 = (value: any) => {
        if (value) {
          loading2.value = true

          options2.value = pageData.firmList
          loading2.value = false
        } else {
          options2.value = []
        }
      }
      // function getFrimList(ob: any, nums: any) {
      //   post({
      //     url: 'org/firmGroup/getFirmInfoByMap',
      //     data: ob,
      //   }).then((result: any) => {
      //     if (result.code === 200) {
      //       if (nums == 1) {
      //         pageData.firmList = result.data
      //       }
      //       if (nums == 2) {
      //         pageData.bmList = result.data
      //       }
      //     } else {
      //       Message.error(result.message)
      //     }
      //   })
      // }
      //公司改变 部门为=空
      const changeGs = (num: any) => {
        if (num == 1) {
          dataForm.firmGroupId = ''
        } else {
          dataForm.firmGroupId = ''
        }
      }
      // 指派人员接口
      function getPersonnel() {
        //查所有的员工
        post({
          url: 'org/hrEmployee/getList',
          data: {
            company_id: pageData.firmId,
            deleteState: 0,
            department_id: pageData.departmentId,
            obsoleteState: 0,
          },
        }).then((res) => {
          if (res.code == 200) {
            pageData.dismantlingSheetNumberList = res.data
          } else {
            Message.error({
              content: res['message'],
              duration: 5000,
            })
          }
        })
      }
      //获取公司部门组列表
      const getFirmGroup = () => {
        get({
          url: '/org/firmGroup/getTreeFirmGroup',
        }).then(({ code, data }) => {
          if (code === 200) {
            pageData.firmList = data
          }
        })
      }
      //计算计件工资
      const calculateSalary = (record: any) => {
        if (record.number != 0 && record.number != undefined && record.number != null) {
          record.pieceMoney = (record.number * parseFloat(record.price)).toFixed(2)
        }
        if (record.weight != 0 && record.weight != undefined && record.weight != null) {
          record.pieceMoney = (record.weight * parseFloat(record.price)).toFixed(2)
        }
        calculatedField()
      }
      //搬运项目名下拉框改变 单价带出
      const changeCpj = (val: any) => {
        let cpjLists = pageData.cpjList.filter((res) => {
          return res.transportName == val
        })
        dataForm.unit = cpjLists[0].unit
        dataForm.price = cpjLists[0].price
        //   let list = pageData.cpjList.filter(function (o: any) {
        //     return o['transportName'] == val
        //   })
        //   if (list.length > 0) {
        //     record.price = list[0]['price']
        //   }
        //   calculateSalary(record)
        // }
        // //计算总重量/条数/计件工资
        // function calculatedField() {
        //   pageData.totalWeight = 0
        //   pageData.totalNumber = 0
        //   pageData.totalWages = 0
        //   pageData.list.forEach(function (o: any) {
        //     if (o['weight'] != undefined && o['weight'] != null) {
        //       pageData.totalWeight += parseFloat(o['weight'])
        //     }
        //     if (o['number'] != undefined && o['number'] != null) {
        //       pageData.totalNumber += parseFloat(o['number'])
        //     }
        //     if (o['pieceMoney'] != undefined && o['pieceMoney'] != null) {
        //       pageData.totalWages += parseFloat(o['pieceMoney'])
        //     }
        //   })
      }
      //作废
      const toVoid = () => {
        if (gridOption.value.getSelectedRows().length == 0) {
          Message.warning({
            content: '请勾选一条数据',
            duration: 5000,
          })
          return
        }
        let rowData = gridOption.value.getSelectedRows()
        rowData.forEach(function (o: any) {
          o['toState'] = 1
        })
        post({
          url: 'pieceData/CarryPiece/update',
          data: rowData,
        })
          .then((res: any) => {
            if (res.code === 200) {
              formRef.value?.resetFields()
              pageData.showAdd = false

              Message.success({
                content: '修改成功',
                duration: 5000,
              })
            } else {
              Message.error({
                content: res.message,
                duration: 5000,
              })
            }
            doRefresh()
          })
          .finally(() => {
            pageData.pageLoading = false
          })
      }
      const huiche = () => {
        doRefresh()
      }
      const onSelect = (dateString: any) => {
        if (dateString[0]) {
          const d1 = new Date(dateString[0])
          const d2 = new Date(dateString[1])
          if (d1 > d2) {
            dateString.reverse()
          }
        }
        pageData.registerTime = dateString[0]
        pageData.registerTime2 = dateString[1]
      }
      const onClear = () => {
        pageData.registerTime = ''
        pageData.registerTime2 = ''
      }
      //  :items="['查询', '新增', '删除', '导出', '作废']"
      const permissionStore = usePermission()
      if (permissionStore.hasPermisson('bygjzdlb.cx')) {
        pageData.btnList.push('查询')
      }
      if (permissionStore.hasPermisson('bygjzdlb.xz')) {
        pageData.btnList.push('新增')
      }
      if (permissionStore.hasPermisson('bygjzdlb.sc')) {
        pageData.btnList.push('删除')
      }
      // if (permissionStore.hasPermisson('bygjzdlb.dc')) {
      //   pageData.btnList.push('导出')
      // }
      // if (permissionStore.hasPermisson('bygjzdlb.zf')) {
      //   pageData.btnList.push('作废')
      // }

      const selectedKeys = ref([])

      const columns = [
        {
          title: '员工',
          dataIndex: 'name',
        },
      ]
      const dataListDeff = ref([])

      const rowSelection: any = reactive({
        type: 'checkbox',
        showCheckedAll: true,
        onlyCurrent: false,
      })

      const jjgzooo = (arryList: any) => {
        let cqxs = 0
        arryList.forEach((res: any) => {
          cqxs += Number(res.workCoefficient)
        })
        arryList.forEach((resg: any) => {
          resg.amount = ((Number(resg.pieceWage) / cqxs) * resg.workCoefficient).toFixed('2')
        })
      }

      const totalNumClick = (val: any) => {
        dataForm.pieceWage = (Number(val) * Number(dataForm.price)).toFixed('2')
      }

      const workChanges = (record: any) => {
        jjgzooo(pageData.list)
      }

      return {
        workChanges,
        totalNumClick,
        rowSelection,
        selectedKeys,
        dataListDeff,
        columns,
        onSelect,
        onClear,
        huiche,
        toVoid,
        changeCpj,
        focusSelCpj,
        handleSearchCpj,
        optionsCpj,
        calculateSalary,
        getFirmGroup,
        options2,
        loading2,
        handleSearch2,
        foucusUseFrim,
        changeGs,
        getPersonnel,
        cascaderRef,
        configCascader,
        changeCascader,
        cascaderRef1,
        changeCascader1,
        openStaff,
        addLine,
        delLine,
        visible,
        handleOk,
        handleCancel,
        localeText1,
        defaultColDef,
        tc,
        tc1,
        total,
        PageSize,
        change1,
        page,
        size,
        deleteHandler,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        selectedRowKeys,
        pagination,
        tableColumns,
        table,
        rowKey,
        pageData,
        queryData,
        selectHandler,
        exports,
        options,
        loading,
        handleSearch,
        focusSel,
        headerShow,
        gridReady,
        s: selectedRowKeys1.selectedRowKeys,
        tableColumns1,
        permissionStore,
        gridReadyw,
        gridOptionw,
      }
    },
    components: { Toolbar, PageTabelLayout, CorporateSectorCascader },
  }
</script>
<style scoped lang="less">
  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }

  :deep(.arco-picker input) {
    padding-left: 0 !important;
  }

  :deep(.arco-picker) {
    padding-left: 0 !important;
  }

  :deep(.arco-picker-separator) {
    padding: 0 !important;
  }
</style>
